package com.zzj.controller;

import com.alibaba.fastjson.JSONObject;
import com.zzj.base.Result;
import com.zzj.entity.Chat;
import com.zzj.entity.ChatFriends;
import com.zzj.model.dto.chat.ChatFriendsCreateDTO;
import com.zzj.service.IChatFriendsService;
import com.zzj.service.IChatService;
import com.zzj.service.RedisService;
import com.zzj.utils.JWTUtil;
import com.zzj.utils.RedisUtil;
import jakarta.annotation.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.util.List;

/**
 * <p>
 * 好友表 前端控制器
 * </p>
 *
 * @author zzj
 * @since 2023-03-05
 */
@RestController
@RequestMapping("/chatFriends")
public class ChatFriendsController {

    @Resource
    private IChatFriendsService chatFriendsService;
    @Resource
    private RedisService redisService;
    @Resource
    private IChatService chatService;

    @Transactional
    @PostMapping("friendsList")
    public Result friendsList(@RequestHeader(value = HttpHeaders.AUTHORIZATION) String token) {
        String username = JWTUtil.getUsername(token);
        List<ChatFriends> list = chatFriendsService.lambdaQuery()
                .eq(ChatFriends::getFromUsername, username)
                .orderByDesc(ChatFriends::getUpdateTime)
                .list();
        list.forEach(one -> {
            String item = one.getToUsername() + ",间隔," + one.getFromUsername();
            int chatNoReadNum = redisService.getChatNoReadNum(item);
            if (chatNoReadNum!=0) {
                one.setNoReadNum(chatNoReadNum);
            }
            JSONObject json = new JSONObject();
            Chat chat = chatService.lastChat(one.getFromUsername(), one.getToUsername());
            if(chat!=null){
                json.put("lastContent", chat.getContent());
                json.put("lastTime", chat.getCreateTime());
                json.put("lastType",chat.getType());
                json.put("lastSize",chat.getSize());
            }
            one.setLast(json.toJSONString());
        });
        return Result.success(list);
    }

    /**
     * 添加好友
     * @param in
     * @return
     */
    @Transactional
    @PostMapping("create")
    public Result create(@RequestBody @Validated ChatFriendsCreateDTO in) {
        ChatFriends one = chatFriendsService.findChatFriend(in.getFromUsername(), in.getToUsername());
        if (one != null) {
            return Result.success(one);
        }
        boolean aBoolean = chatFriendsService.mutualCreateFriend(in);
        if (!aBoolean) {
            return Result.error("好友创建失败");
        }
        one = chatFriendsService.findChatFriend(in.getFromUsername(), in.getToUsername());
        return Result.success(one);
    }

}
